import axios from 'axios';
import { ElMessage } from 'element-plus';
import { SERVER_IP, SERVER_PORT } from '@/config'

// 创建一个 axios 实例
const baseURL = `http://${SERVER_IP}:${SERVER_PORT}/api/`
const request = axios.create({
  baseURL,
  timeout: 20000 // 请求超时时间
});

// 请求拦截器
request.interceptors.request.use(
  config => {
    // 从 localStorage 中获取 token 和 tokenExpire
    const token = localStorage.getItem('token');
    const tokenExpire = localStorage.getItem('tokenExpire');

    // 检查 token 是否存在且未过期
    if (token && tokenExpire && Date.now() < parseInt(tokenExpire)) {
      // 如果 token 有效，将其添加到请求头中
      config.headers['Authorization'] = `Bearer ${token}`;
    }

    return config;
  },
  error => {
    // 请求错误处理
    console.log(error);
    return Promise.reject(error);
  }
);

// 响应拦截器
request.interceptors.response.use(
  response => {
    const res = response.data;
    if (res.message) { showMessage(res.message, 'success') }
    return Promise.resolve(res);
  },
  error => {
    if(error.response.status === 401){
      showMessage('登录过期，请重新登录', 'error')
      loginExpire()
    }else{
      console.log(error)
      showMessage(error.response.data.message || error.message, 'error')
    }
    return Promise.reject(error);
  }
);

const loginExpire = ()=> {
  localStorage.removeItem('token');
  localStorage.removeItem('tokenExpire');
  window.location.href = '/login';
}

const showMessage = (message, type)=> {
  ElMessage({
    message,
    type,
    duration: 5 * 1000
  });
}

export default request;